import { computed, onScopeDispose, reactive, readonly, toRef } from 'vue'

export function useCountdown(initialSeconds = 60, options = {}) {
  const {
    autoStart = false,
    interval = 1000,
    onEnd,
    onStart,
    onPause
  } = options

  let timer = undefined

  const defaultState = {
    count: initialSeconds,
    isRunning: false
  }

  const state = reactive({ ...defaultState })
  const isEnd = computed(() => state.count <= 0)

  const start = () => {
    if (state.isRunning || isEnd.value) {
      return
    }
    if (timer) {
      clearTimer()
    }

    timer = setInterval(() => {
      state.count--
      if (isEnd.value) {
        pause()
        onEnd?.()
      }
    }, interval)

    state.isRunning = true
    onStart?.()
  }

  const pause = () => {
    if (!state.isRunning) {
      return
    }
    state.isRunning = false
    clearTimer()
    onPause?.()
  }

  const reset = () => {
    clearTimer()
    state.count = defaultState.count
    state.isRunning = defaultState.isRunning
    autoStart && start()
  }

  const clearTimer = () => {
    window.clearInterval(timer)
    timer = undefined
  }

  autoStart && start()
  onScopeDispose(clearTimer)

  return {
    count: readonly(toRef(state, 'count')),
    isRunning: readonly(toRef(state, 'isRunning')),
    start,
    pause,
    reset
  }
}
